<?php
namespace Index\Controller;
use Think\Controller;
use Think\Upload;
use Vendor\ThinkImage\ThinkImage;
use Common\Common\Tree;
// use Index\Controller\CommonController;

class CourseController extends Controller {

    public function indexAction(){
        if(isset($_POST['uid'])){
            $uid = $_POST['uid'];
            $_SESSION['uid']=$uid;
        }
        if(!isset($_SESSION['uid'])){
            $this->error('还没有登录，请先登录再进行访问',U('Index/Login/index'),1);
        }

    	$uid = I('session.uid');

        //分类树
        $Model = M();
        $sqlCategory = "select * from category";
        $category= $Model->query($sqlCategory);
        $tree = new tree();
        $category = $tree->categorytree($category);
      
        $this->assign('category',$category);
     
        $sql = "select face from user";
		$userInfo = $Model->query($sql);
        $userInfo = $userInfo[0];
        $this->assign('userInfo',$userInfo); 

        $this->display();
    }

    //发布课程的ajax
    public function publishAction(){
        if(!IS_AJAX){
            $data = "非法的请求方式";
           $this->ajaxReturn($data);
        }

        $uid = $_SESSION['uid'];
        $postData = I('post.');

        $Model = M();

         //验证具体课程分类
        $sql = "select * from category where id ='{$postData["categoryId"]}'";
        $category= $Model->query($sql);
        if($category[0]['fid'] == 0) {
            $data = "请选择具体课程分类";
            $this->ajaxReturn($data);
        }

        //验证课程名称
        $length = strlen($postData['name']);
        if($length < 4 || $length> 60) {
            $data = "课程名称限定2-30个汉字或者4-60字符";
            $this->ajaxReturn($data);
        }

        //验证课程价格
        $test="/^\d+\.{1}\d{2}?$/";
        if(!preg_match($test, $postData['cost'])) {
            $data = "课程价格只允许格式为0.00的数字";
            $this->ajaxReturn($data);
        }   

        //验证总课时
        $test ='/^[1-9]\d{0,2}$/';
        if(!preg_match($test, $postData['hours'])) {
            $data = "课程总课时只允许为1-999的整数";
            $this->ajaxReturn($data);
        }   
         
        //验证学习有效期
        $test ='/^\d{1,2}$/';
         if(!preg_match($test, $postData['expiretime']) || $postData['expiretime']<1 ) {
            $data = "学习有效期只允许为1-99的整数";
            $this->ajaxReturn($data);
        }   
            
        //验证购买人数
        $test ='/^\d{1,3}$/';
        if(!preg_match($test, $postData['studentlimit']) || $postData['studentlimit']<1) {
            $data = "购买人数只允许为1-999的整数";
            $this->ajaxReturn($data);
        } 

        //验证教室容量
        $test ='/^\d{1,3}$/';
        if(!preg_match($test, $postData['classroomcapacity']) || $postData['classroomcapacity']<1 || $postData['classroomcapacity']>200) {
            $data = "教室容量只允许为1-200的整数";
            $this->ajaxReturn($data);
        } 

         //验证适合人群
        if(empty($postData['people'])) {
            $data = "请填写适合人群";
            $this->ajaxReturn($data);
        }

        //验证老师姓名
        if(empty($postData['teachername'])) {
            $data = "请填写老师姓名";
            $this->ajaxReturn($data);
        }

         //验证教师技能
        if(empty($postData['skill'])) {
            $data = "请填写个人技能，每个技能之间请以逗号隔开";
            $this->ajaxReturn($data);
        }

        //验证老师简介
        if(empty($postData['brief'])) {
            $data = "请填写老师简介";
            $this->ajaxReturn($data);
        }         

        //验证课程详情
        if(empty($postData['content'])) {
            $data = "请填写课程详情";
            $this->ajaxReturn($data);
        }

        //验证课程标签
        if(empty($postData['tag'])) {
            $data = "请填写课程标签，每个标签之间请以逗号隔开";
            $this->ajaxReturn($data);
        }

        //验证课程简介
        if(empty($postData['introduction'])) {
            $data = "请填写课程简介";
            $this->ajaxReturn($data);
        } 
        
        //验证增值服务
        if(empty($postData['service'])) {
            $data = "请填写增值服务";
            $this->ajaxReturn($data);
        }

        //回放类型
        if(empty($postData['playbacktype'])){
            $data = "请填写回放类型";
            $this->ajaxReturn($data);
        }


        if($postData['isteacher'] != 1) {
            $data = "教师头像未上传";
            $this->ajaxReturn($data);
        } 

        if($postData['ispicture'] != 1) {
            $data = "教师头像未上传";
            $this->ajaxReturn($data);
        }

        // 教师头像参数
        $arr = array(
            'x' => $postData['x'],
            'y' => $postData['y'],
            'w' =>$postData['w'],
            'h' => $postData['h'],
            'src' =>$postData['src']
        );

        // 需要裁剪的头像地址,即上传头像所在位置
        $path = './Teacher/';
        $teacherUrl = $this->_cropImg($arr,$path);
        $this->assign('teacherUrl',$teacherUrl);

        // 课程封面参数
        $arr = array(
            'x' => $postData['x1'],
            'y' => $postData['y1'],
            'w' =>$postData['w1'],
            'h' => $postData['h1'],
            'src' =>$postData['src1']
        );
        
        //需要裁剪的课程封面地址,即上传封面所在位置
        $path = './Picture/';
        $courseUrl = $this->_cropImg($arr,$path);
        $this->assign('courseUrl',$courseUrl);
        
        $time =time();
        $sql = "insert into course(coursename,categoryid,price,lessonnum,expiretime,studentnum,maxStudentnum,picture,introduction,userid,createtime,people,service,playbacktype,detail) values('{$postData['name']}','{$postData['categoryId']}','{$postData['cost']}','{$postData['hours']}','{$postData['expiretime']}','{$postData['studentlimit']}','{$postData['classroomcapacity']}','{$courseUrl}','{$postData['introduction']}','{$uid}','{$time}','{$postData['people']}','{$postData['service']}','{$postData['playbacktype']}','{$postData['content']}')";
        $Model->execute($sql);
        $id = $Model->getLastInsID();


        $sql = "insert into tag(tagcontent,courseid) values('{$postData['tag']}','{$id}')";
        $Model->execute($sql);

        $sql = "insert into teacher(teachername,brief,teacherface,courseid,skill) values('{$postData['teachername']}','{$postData['brief']}','{$teacherUrl}','{$id}','{$postData['skill']}')";
        $Model->execute($sql);

        $data ='发布成功';
        $this->ajaxReturn($data);

    }


     /**
     *百度编辑器
     */
    public function ueditorAction(){
        $data = new \Org\Util\Ueditor();
        echo $data->output();
    }

    //上传授课老师头像
	public function uploadImgAction(){
		$upload = new Upload(C('UPLOAD_CONFIG_TEACHER'));	// 实例化上传类
		//头像目录地址
		$path = './Teacher/';
       
		if(!$info=$upload->upload()) {						
		// 上传错误提示错误信息
			$this->ajaxReturn(array('status'=>0,'info'=>$upload->getError()));
		}else{	
			// 上传成功 获取上传文件信息		
			$url = $info['Filedata']['savename'];
		
			$temp_size = getimagesize($path.$url);
			
			if($temp_size[0] < 100 || $temp_size[1] < 100){
			//判断宽和高是否符合头像要求
				$this->ajaxReturn(array('status'=>0,'info'=>'图片宽或高不得小于100px！'));
			}
			$this->ajaxReturn(array('status'=>1,'path'=>__ROOT__.'/Teacher/'.$url));
		}
	}


    //上传课程封面
	public function uploadImgCourseAction(){
		$upload = new Upload(C('UPLOAD_CONFIG_COURSE'));	// 实例化上传类
		//头像目录地址
		$path = './Picture/';
		if(!$info=$upload->upload()) {						
		// 上传错误提示错误信息
			$this->ajaxReturn(array('status'=>0,'info'=>$upload->getError()));
		}else{	
			// 上传成功 获取上传文件信息
			
			$url = $info['Filedata']['savename'];
		
			$temp_size = getimagesize($path.$url);
		
			if($temp_size[0] < 145 || $temp_size[1] < 92){
			//判断宽和高是否符合头像要求
				$this->ajaxReturn(array('status'=>0,'info'=>'图片宽不得小于145或高不得小于92px！'));
			}
			$this->ajaxReturn(array('status'=>1,'path'=>__ROOT__.'/Picture/'.$url));
		}
	}


	//裁剪并保存头像、课程封面
	public function _cropImg($params,$path){
		
		// if(!isset($params) && empty($params)){
		// 	// $this->error('参数错误！');
		// 	return '参数错误！';
		// }
		//要保存的图片
		$real_path = $path.uniqid().'.jpg';
		//临时图片地址
		$src = $params['src'];
		$srcArr = explode('/',$src);
		$pic_path = $path.end($srcArr);
		//实例化裁剪类
		$Think_img = new ThinkImage(THINKIMAGE_GD);
		//裁剪原图得到选中区域
		$Think_img->open($pic_path)->crop($params['w'],$params['h'],$params['x'],$params['y'])->save($real_path);
		@unlink($pic_path);
		$pic_path = substr($real_path, 1);
		return $pic_path;
	}

    //某个课程的编辑页面
    public function editAction(){

        if(isset($_POST['uid'])){
            $uid = $_POST['uid'];
            $_SESSION['uid']=$uid;
        }

        if(!isset($_SESSION['uid'])){
            $this->error('还没有登录，请先登录再进行访问',U('Index/Login/index'),1);
        }

        $uid = I('session.uid');
        $id = I('get.id');
        $Model = M();

        //页面展示信息
        $sql = "select t1.coursename,t1.categoryid,t1.price,t1.lessonnum,t1.expiretime,t1.studentnum,t1.maxStudentnum,t1.picture,t1.introduction,t1.people,t1.service,t1.playbacktype,t1.detail,t2.teachername,t2.brief,t2.teacherface,t2.courseid,t2.skill,t3.tagcontent from course t1 left join teacher t2 on t1.id = t2.courseid left join tag t3 on t1.id =t3.courseid where t1.id = '{$id}'";
        $courseInfo = $Model->query($sql);
        $courseInfo = $courseInfo[0];
        $courseInfo['detail'] = htmlspecialchars_decode($courseInfo['detail']);
        $this->assign('courseInfo',$courseInfo);
    
        //分类树      
        $sql = "select * from category";
        $category= $Model->query($sql);
        $tree = new tree();
        $category = $tree->categorytree($category);  
        $this->assign('category',$category); 

        //个人信息
        $sql = "select face from user";
        $userInfo = $Model->query($sql);
        $userInfo = $userInfo[0];
        $this->assign('userInfo',$userInfo); 

        $this->display();     
    }

    //编辑课程的ajax
    public function modifyAction(){
        if(!IS_AJAX){
            $data ="非法的请求方式";
           $this->ajaxReturn($data);
        }

        $uid = $_SESSION['uid'];
        $postData = I('post.');
        $Model = M();

         //验证具体课程分类
        $sql = "select * from category where id ='{$postData["categoryId"]}'";
        $category= $Model->query($sql);
        if($category[0]['fid'] == 0) {
            $data ="请选择具体课程分类";
            $this->ajaxReturn($data);
        }

        //验证课程名称
        $length = strlen($postData['name']);
        if($length < 4 || $length> 60) {
            $data ="课程名称限定2-30个汉字或者4-60字符";
            $this->ajaxReturn($data);
        }

        //验证课程价格
        $test="/^\d+\.{1}\d{2}?$/";
        if(!preg_match($test, $postData['cost'])) {
            $data ="课程价格只允许格式为0.00的数字";
            $this->ajaxReturn($data);
        }   

        //验证总课时
        $test ='/^[1-9]\d{0,2}$/';
        if(!preg_match($test, $postData['hours'])) {
            $data ="课程总课时只允许为1-999的整数";
            $this->ajaxReturn($data);
        }   
         
        //验证学习有效期
        $test ='/^\d{1,2}$/';
         if(!preg_match($test, $postData['expiretime']) || $postData['expiretime']<1 ) {
            $data ="学习有效期只允许为1-99的整数";
            $this->ajaxReturn($data);
        }   
            
        //验证购买人数
        $test ='/^\d{1,3}$/';
        if(!preg_match($test, $postData['studentlimit']) || $postData['studentlimit']<1) {
            $data ="购买人数只允许为1-999的整数";
            $this->ajaxReturn($data);
        } 

        //验证教室容量
        $test ='/^\d{1,3}$/';
        if(!preg_match($test, $postData['classroomcapacity']) || $postData['classroomcapacity']<1 || $postData['classroomcapacity']>200) {
            $data ="教室容量只允许为1-200的整数";
            $this->ajaxReturn($data);
        } 

         //验证适合人群
        if(empty($postData['people'])) {
            $data ="请填写适合人群";
            $this->ajaxReturn($data);
        }

        //验证老师姓名
        if(empty($postData['teachername'])) {
            $data ="请填写老师姓名";
            $this->ajaxReturn($data);
        }

         //验证教师技能
        if(empty($postData['skill'])) {
            $data ="请填写个人技能，每个技能之间请以逗号隔开";
            $this->ajaxReturn($data);
        }

        //验证老师简介
        if(empty($postData['brief'])) {
            $data ="请填写老师简介";
            $this->ajaxReturn($data);
        }         

        //验证课程详情
        if(empty($postData['content'])) {
            $data ="请填写课程详情";
            $this->ajaxReturn($data);
        }

        //验证课程标签
        if(empty($postData['tag'])) {
            $data ="请填写课程标签，每个标签之间请以逗号隔开";
            $this->ajaxReturn($data);
        }

        //验证课程简介
        if(empty($postData['introduction'])) {
            $data ="请填写课程简介";
            $this->ajaxReturn($data);
        } 
        
        //验证增值服务
        if(empty($postData['service'])) {
            $data ="请填写增值服务";
            $this->ajaxReturn($data);
        }

        //回放类型
        if(empty($postData['playbacktype'])){
            $data ="请填写回放类型";
            $this->ajaxReturn($data);
        }

        // 教师头像
        if($postData['isteacher'] == 1) {
            $arr = array(
                'x' => $postData['x'],
                'y' => $postData['y'],
                'w' =>$postData['w'],
                'h' => $postData['h'],
                'src' =>$postData['src']
            );
            // 需要裁剪的头像地址,即上传头像所在位置
            $path = './Teacher/';
            $teacherUrl = $this->_cropImg($arr,$path);
            $this->assign('teacherUrl',$teacherUrl);
            $sql ="update teacher set teacherface = '{$teacherUrl}' where courseid ='{$postData["courseid"]}'";
            $Model->execute($sql); 
        } 

        // 课程封面
        if($postData['ispicture'] == 1) {
            $arr = array(
                'x' => $postData['x1'],
                'y' => $postData['y1'],
                'w' =>$postData['w1'],
                'h' => $postData['h1'],
                'src' =>$postData['src1']
            );
            //需要裁剪的课程封面地址,即上传封面所在位置
            $path = './Picture/';
            $courseUrl = $this->_cropImg($arr,$path);
            $this->assign('courseUrl',$courseUrl);
            $sql ="update course set picture = '{$courseUrl}' where id ='{$postData["courseid"]}'";
            $Model->execute($sql); 
        } 

        $sql = "select t1.coursename,t1.categoryid,t1.price,t1.lessonnum,t1.expiretime,t1.studentnum,t1.maxStudentnum,t1.picture,t1.introduction,t1.people,t1.service,t1.playbacktype,t1.detail,t2.teachername,t2.brief,t2.teacherface,t2.courseid,t2.skill,t3.tagcontent from course t1 left join teacher t2 on t1.id = t2.courseid left join tag t3 on t1.id =t3.courseid where t1.id = '{$postData["courseid"]}'";
        $courseInfo = $Model->query($sql);
        $courseInfo = $courseInfo[0];


        if($courseInfo['coursename'] != $postData['name']
            || $courseInfo['categoryid'] != $postData['categoryId']
            || $courseInfo['price'] != $postData['cost']
            || $courseInfo['lessonnum'] != $postData['hours']
            || $courseInfo['expiretime'] != $postData['expiretime']
            || $courseInfo['studentnum'] != $postData['studentlimit']
            || $courseInfo['maxStudentnum'] != $postData['classroomcapacity']
            || $courseInfo['people'] != $postData['people']
            || $courseInfo['detail'] != $postData['content']
            || $courseInfo['introduction'] != $postData['introduction']
            || $courseInfo['service'] != $postData['service']
            || $courseInfo['playbacktype'] != $postData['playbacktype']
        ){
            $sql ="update course set coursename = '{$postData['name']}',categoryid = '{$postData['categoryId']}',price = '{$postData['cost']}',lessonnum = '{$postData['hours']}',expiretime = '{$postData['expiretime']}',studentnum = '{$postData['studentlimit']}',maxStudentnum = '{$postData['classroomcapacity']}',people = '{$postData['people']}',detail = '{$postData['content']}',introduction = '{$postData['introduction']}',service = '{$postData['service']}',playbacktype = '{$postData['playbacktype']}'  where id ='{$postData["courseid"]}'";
            $Model->execute($sql); 
        }

        if($courseInfo['teachername'] != $postData['teachername'] 
            || $courseInfo['brief'] != $postData['brief']
            || $courseInfo['skill'] != $postData['skill']){
            $sql ="update teacher set teachername = '{$postData['teachername']}',brief = '{$postData['brief']}',skill = '{$postData['skill']}' where courseid ='{$postData["courseid"]}'";
            $Model->execute($sql);
        }
        
        if($courseInfo['tagcontent'] != $postData['tag']){
            $sql ="update tag set tagcontent = '{$tag}' where courseid ='{$postData["courseid"]}'";
            $Model->execute($sql);
        }  
        
        $data ="修改成功";
        $this->ajaxReturn($data);

    }



    //课程的管理页面
    public function contentAction(){

        if(!isset($_SESSION['uid'])){
            $this->error('还没有登录，请先登录再进行访问',U('Index/Login/index'),1);
        }
        $uid = I('session.uid');
        $Model = M();
        $sql = "select count(*) as num from course where userid ='{$uid}'";
        $count = $Model->query($sql);
        $Page = new \Think\Page($count[0]['num'],7);// 实例化分页类 传入总记录数和每页显示的记录数(7)
        $show = $Page->show();// 分页显示输出
        $this->assign('page',$show);

      
        $sql = "select face,username from user where id ='{$uid}'";
        $userInfo = $Model->query($sql);
        $userInfo = $userInfo[0];
        $this->assign('userInfo',$userInfo); 
       
        $sql = "select t1.id,t1.coursename,t1.categoryid,t1.createtime,t1.price,t1.picture,t1.lessonnum,t2.applynum from course t1 left join (select courseid,count(*) as applynum from application group by courseid) as t2 on t1.id = t2.courseid where t1.userid = '{$uid}' order by t1.createtime desc limit {$Page->firstRow},{$Page->listRows}";
        $courseInfo = $Model->query($sql);
        $this->assign('courseInfo',$courseInfo);


        $sql = "select * from category where fid = 0 ";
        $categoryInfo = $Model->query($sql);
        $this->assign('categoryInfo',$categoryInfo);

        $this->display('content');
    }


     //课程详情
    public function listAction(){

        if(!isset($_SESSION['uid'])){
            $this->error('还没有登录，请先登录再进行访问',U('Index/Login/index'),1);
        }

        $uid = I('session.uid');
        $id = I('get.id');
        $this->assign('courseid',$id); 
        $Model = M();
        $sql = "select coursename from course where id = '{$id}' and userid = '{$uid}'";
        $courseInfo = $Model->query($sql);
        if(empty($courseInfo)){
            @header("http/1.1 404 not found"); 
            @header("status: 404 not found"); 
            echo '404 not found';//直接输出页面错误信息 
            exit(); 
        }
        $this->assign('courseInfo',$courseInfo); 

        $sql = "select face,username from user where id ='{$uid}'";
        $userInfo = $Model->query($sql);
        $userInfo = $userInfo[0];
        $this->assign('userInfo',$userInfo);  

        

        $sql = "select * from courselist where courseid = '{$id}' order by starttime asc";
        $list = $Model->query($sql);
        $this->assign('list',$list); 
        // $this->assign('post',$post); 

        // $sql = "select id,coursename,categoryid,createtime,price,picture,lessonnum from course where userid = '{$uid}'";
        // $courseInfo = $Model->query($sql);
        // $this->assign('courseInfo',$courseInfo);
        // $sql = "select * from category where fid = 0 ";
        // $categoryInfo = $Model->query($sql);
        // $this->assign('categoryInfo',$categoryInfo);
       
        
        $this->display('list');
    }

      //添加课程详情的ajax
    public function addAction(){
        // $id = $_SESSION['uid'];
        if(!IS_AJAX){
            $data ="非法的请求方式";
           $this->ajaxReturn($data);
        }
        $post = I('post.');
        $courseid = $post['courseid'];  
        $Model = M();
        $sql = "select t1.lessonnum,count(*) count from course t1 left join courselist t2 on t1.id = t2.courseid where t1.id ='{$courseid}' group by t2.courseid";
        $course = $Model->query($sql);
        if($course[0]['lessonnum'] == $course[0]['count']){
            $this->ajaxReturn('已超出你设置的课程总节数，若想增加，请返回修改课程信息');
        }
        
        $starttime = strtotime($post['starttime']);
        $endtime = strtotime($post['endtime']);      
        $time = $endtime - $starttime;
        if(empty($post['starttime']) || empty($post['endtime']) || $time>3600*4 || $time<=1000){
            $this->ajaxReturn('请设置合理的时间');
        }
        if(empty($post['content'])){
            $this->ajaxReturn('请填写本节课程介绍');
        }
        
        $content = $post['content']; 
        
        $sql = "insert into courselist(courseid,starttime,endtime,content) values('{$courseid}','{$starttime}','{$endtime}','{$content}')";
        $Model->execute($sql);
        $id = $Model->getLastInsID();

        $start = date('Y-m-d H:i',$starttime);  
        $end = date('H:i',$endtime);
     
        $data="<li style='list-style:none;width:960px;height:50px;margin:10px;border:1px solid red;padding:10px'><input type='hidden' name='courseid' value='$courseid'><input type='hidden' name='courselistid' value='$id'><div style='height:25px'><button type='button' id='edit' style='width:100px;background-color:#5bc79d'>编辑</button>&nbsp;&nbsp;&nbsp;<span style='font-size:14px;'>时间：</span><span style='font-size:14px;margin:10px'>$start - $end</span></div><a id='delete' href='' onclick='return confirm(确定删除?);'><button type='button' style='width:100px;background-color:#5bc79d'>删除</button></a>&nbsp;&nbsp;&nbsp;<span style='font-size:14px'>本节课程介绍：</span><span style='margin:10px;'>$content</span></li>"; 
        $this->ajaxReturn($data);
    }
// 

     //删除课程详情
    // public function deletelistAction(){
    //     $id = I('get.id');
    //     var_dump($id);
       
    // }


     //课程展示
    public function showAction(){
        $uid = I('session.uid');
        $id = I('get.id');
        $this->assign('courseid',$id );
        
        $Model = M();
        $sql = "select face,username from user where id ='{$uid}'";
        $userInfo = $Model->query($sql);
        $userInfo = $userInfo[0];
        $this->assign('userInfo',$userInfo);

        $sql = "select t1.coursename,t1.categoryid,t1.picture,t1.price,t1.lessonnum,t1.introduction,t1.people,t1.playbacktype,t1.service,t1.detail,t2.categoryname,t2.fid,t3.id,t3.teachername,t3.brief,t3.teacherface from course t1 left join category t2 on t1.categoryid = t2.id left join teacher t3 on t1.id = t3.courseid where t1.id ='{$id}'";
        $courseInfo = $Model->query($sql);
        $courseInfo = $courseInfo[0];
        $courseInfo['detail'] = htmlspecialchars_decode($courseInfo['detail']);
        $this->assign('courseInfo',$courseInfo);

        //收藏人数
        $sql = "select * from (select courseid,count(*) num from course_favorite group by courseid) t1 where t1.courseid = '{$id}'";
        $favorite = $Model->query($sql);
        $favorite = $favorite[0];
        $this->assign('favorite',$favorite);
        //免费课程
        $sql = "select t1.id,t1.coursename,t1.picture,t2.teachername from course t1 left join teacher t2 on t1.id = t2.courseid where t1.price = 0 limit 8";
        $freeCourse = $Model->query($sql);
        $this->assign('freeCourse',$freeCourse);

        //推荐课程
        $sql = "select t1.id,t1.coursename,t1.price,t1.picture,t2.teachername from course t1 left join teacher t2 on t1.id = t2.courseid where t2.teachername = '{$courseInfo['teachername']}' limit 3";
        $recommendCourse = $Model->query($sql);
        $this->assign('recommendCourse',$recommendCourse);

        //一级分类
        $sql = "select categoryname from category where id ='{$courseInfo['fid']}'";
        $categoryInfo = $Model->query($sql);
        $categoryInfo = $categoryInfo[0];
        $this->assign('categoryInfo',$categoryInfo);

        //课程标签
        $sql = "select tagcontent from tag where courseid ='{$id}'";
        $tagInfo = $Model->query($sql);
        $this->assign('tagInfo',$tagInfo);

        $sql = "select content,starttime,endtime from courselist where courseid ='{$id}'";
        $courselistInfo = $Model->query($sql);
        $this->assign('courselistInfo',$courselistInfo);
        

        //听课有效期至某一天
        $max = max($courselistInfo);
        $endtimeMax = $max['endtime']+3600*24*15;
        $this->assign('endtimeMax',$endtimeMax);

        //最近直播
        $arr =array();
        foreach ($courselistInfo as $key => $value) {
            if($value['endtime'] > time()){    
                $arr[$key] = $value['endtime'];
            }
        }
        if(!empty($arr)){
            $min = min($arr);  
            $key = array_search($min,$arr);        
        }else{
            $key =100; 
        }
        $this->assign('key',$key);   

        $sql = "select count(*) as applynum  from application where courseid ='{$id}'";
        $apply = $Model->query($sql);
        $this->assign('apply',$apply);



        $this->display();
    }

    //领取报名 的ajax
    public function receiveAction(){
        if(!IS_AJAX){
            $data = "非法的请求方式";
           $this->ajaxReturn($data);
        }

        $uid = I('session.uid');
        if(empty($uid)){
            $data = "nologin";
            $this->ajaxReturn($data);
        }
        $id = I('get.id');
        $Model = M();
        $sql = "select id from application where uid = '{$uid}' and courseid = '{$id}'";
        $apply = $Model->query($sql);
        if(empty($apply)){
            $time =time();
            $sql = "insert into application(uid,courseid,createtime) values('{$uid}','{$id}','{$time}')";
            $Model->execute($sql);
             // $data = $Model->execute($sql);
            $data = "领取成功";
            
        }else{
            $data = "你已领取该课程,无需重复申请";
        }

        $this->ajaxReturn($data);

    }


    //登录 的ajax
    public function loginAction(){
        if(!IS_AJAX){
            $data = "非法的请求方式";
            $this->ajaxReturn($data);
        }

        $username = I('get.userName');
        $password = md5(I('get.password'));
        $Model = M();
        $isName = $Model->query("select groupId,username,id,face from user where username ='{$username}'  and password ='{$password}'");
        $isMail = $Model->query("select groupId,username,id,face from user where email ='{$username}'  and password ='{$password}'");
        $isMobile = $Model->query("select groupId,username,id,face from user where phone ='{$username}'  and password ='{$password}'");
        // if ($isName[0]['gid'] == 3 || $isMail[0]['gid'] == 3 || $isMobile[0]['gid'] == 3) {
        //     $data = "你已被管理设置权限，无法登录";
        //     $this->ajaxReturn($data);
        // }

        if (empty($isName) && empty($isMail) && empty($isMobile)) {
            $data ="error.login.userNameIsError";//用户名或密码错误
            $this->ajaxReturn($data);
        } else {
            if(!empty($isName)){
                $userInfo =$isName[0];
            }elseif(!empty($isMail)){
                $userInfo =$isMail[0];
            }else{
                $userInfo =$isMobile[0];
            }
            $_SESSION['username'] = $userInfo['username'];
            $_SESSION['uid'] = $userInfo['id'];
            $_SESSION['gid'] = $userInfo['groupId'];
            $_SESSION['face'] = $userInfo['face'];
            $loginTime = time();
            $Model->execute("update user set loginTime = '{$loginTime}' where id ='{$_SESSION['uid']}'");
//            session_start();
//            setcookie(session_name(),session_id(),time()+60);

            $data ="success";//登录成功
            $this->ajaxReturn($data);
        }


    }

    //初始判断是否收藏的ajax
    public function loadFavoritesAction(){
        if(!IS_AJAX){
            $data = "非法的请求方式";
            $this->ajaxReturn($data);
        }
        $uid = I('session.uid');
        $id = I('get.id');
        $Model = M();
        $sql = "select * from course_favorite where userid = '{$uid}' and courseid = '{$id}'";
        $favorite = $Model->query($sql);
        if(empty($favorite)){
            $data = array(
                'success' => 0,
                'messageInfo'=>'未收藏'
            );  
        }else{
            $data = array(
                'success' => 1,
                'messageInfo'=>'已收藏'
            );
        }
        $this->ajaxReturn($data);

    }

     //加入收藏的ajax
    public function addFavoritesAction(){
        if(!IS_AJAX){
            $data = "非法的请求方式";
            $this->ajaxReturn($data);
        }
        $uid = I('session.uid');
        if(empty($uid)){
            $data = array(
                'success' => 0,
                'messageInfo'=>'用户未登录'
            );
            $this->ajaxReturn($data);
        }
        $id = I('get.id');
        $Model = M();
        $sql = "select * from course_favorite where userid = '{$uid}' and courseid = '{$id}'";
        $favorite = $Model->query($sql);
        if(empty($favorite)){
            $data = array(
                'success' => 1,
                'messageInfo'=>'未收藏'
            );
            $time = time();
            $sql = "insert into course_favorite(courseid,userid,createtime) values('{$id}','{$uid}','{$time}')";
            $Model->execute($sql);
        }else{
            $data = array(
                'success' => 0,
                'messageInfo'=>'已收藏'
            );
        }
        $this->ajaxReturn($data);

    }


    //取消收藏的ajax
    public function delFavoritesAction(){
        if(!IS_AJAX){
            $data = "非法的请求方式";
            $this->ajaxReturn($data);
        }
        $uid = I('session.uid'); 
        $id = I('get.id');
        $Model = M();
        $sql = "delete from course_favorite where userid = '{$uid}' and courseid = '{$id}' ";
        $Model->execute($sql);
        $data = array(
                'success' => 1,
                'messageInfo'=>'已删除'
            );
        $this->ajaxReturn($data);

    }


}